<?php
/**
 * CreateTime: 2023/4/14 15:06
 */

namespace App\Http\Controllers\MeMediator;

use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Func\ResponseFunc;
use App\Func\TokenFuc;
use App\Models\File\FileModel;
use App\Models\MeLawCase\MeLawCase;
use App\Models\MeMediator\MediationAgreementModel;
use App\Tools\DocxGenerator\FormatDocx;

class MeMediatorAgreementController
{
    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function setMeMediatorAgreementTemplate(): \Illuminate\Http\JsonResponse
    {
        $data = request()->all();
        $mediationAgreementModel = new MediationAgreementModel();
        // 获取当前是当月的第几个调解函
        $str = $mediationAgreementModel->getTheSameMonthAgreementCount()+1;
        $str = str_pad($str, 3, '0', STR_PAD_LEFT);
        $data['template_data_json_str'] = json_decode($data['template_data_json_str'],true);
        $data['template_data_json_str']['idx'] = $str;
        $data['template_data_json_str'] = json_encode($data['template_data_json_str']);
        // 检查当前文件是否已经生成调解函 如果没有生成则生成调解函
        $lawCaseInfo = (new MeLawCase())->getById($data['law_case_id'],['law_case_code']);
        $mediationAgreement = $mediationAgreementModel->getByLawCaseId($data['law_case_id'],["file_id"]);
        if(isset($mediationAgreement['file_id'])){
            $fileInfo = (new FileModel())->getFileById($mediationAgreement['file_id']);
            return ResponseFunc::returnJson(
                'ok',
                [
                    'file_ext'=>"pdf",
                    'file_id' => $fileInfo['file_id'],
                    'file_mime_type' => 'application/pdf',
                    'file_name' => $fileInfo['file_name'],
                    'file_url' => $fileInfo['file_url']
                ],
                '获取调解函成功',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }
        $fileName = $lawCaseInfo['law_case_code'];
        return ResponseFunc::returnJson(
            'ok',
            $this->formatMeMediatorAgreementTemplate($fileName,$data['template_data_json_str'],[
                'law_case_id' => $data['law_case_id'],
                'owner_id' => TokenFuc::getCurrentStaffInfo()['staff_id'],
                'idx' => "川0105民诉前调XZCM".substr(date("Ym"),2).$str."号",
            ]),
            '生成调解函成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    private function formatMeMediatorAgreementTemplate($filename,$config,$ext)
    {
        $path = storage_path('app/defaultTemplate/tjh_template.docx');
        // 根据客户名称和类型生成文件名
        $fileName = $filename;
        $fileExt = "docx";
        $fileMimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        $fileUrl = FormatDocx::formatClientEvaluationTemplateReplace(
            $config,
            $path,
            [
                "file_name"=> $fileName,
                "create_at"=> time(),
                "file_ext"=> $fileExt,
            ]
        );
        $fileModel =  (new FileModel());
        $id = $fileModel->insertGetId([
            'file_name'=>$fileName.".".$fileExt,
            'file_url'=>$fileUrl,
            'file_ext'=>$fileExt,
            'file_mime_type' =>$fileMimeType,
            'created_at' => time(),
            'parent_id' => 0
        ]);

        $path = FormatDocx::wordToPdf(
            $fileUrl,
            $fileName.".".$fileExt
        );

        $time = time();
        $pdfId = $fileModel->insertGetId(
            [
                'file_name'=>$fileName.".pdf",
                'file_url'=>$path['newPath'],
                'file_ext'=>"pdf",
                'file_mime_type' => "application/pdf",
                'created_at' => $time,
                'parent_id' =>$id
            ]
        );

        // 生成以后push到当月新增表里
        (new MediationAgreementModel())->add([
            'law_case_id' => $ext['law_case_id'],
            'file_id' => $pdfId,
            'owner_id' => $ext['owner_id'],
            'mediation_agreement_code' => $ext['idx']
        ]);

        return [
            'file_id' => $pdfId,
            'file_name'=>$fileName.".pdf",
            'file_url'=>$path['newPath'],
            'file_ext'=>"pdf",
            'file_mime_type' => "application/pdf"
        ];
    }
}